/**
 * 前序迭代遍历，交换每个节点的左右子节点
 * @param {TreeNode} root
 * @return {TreeNode}
 */

const reverse = node => {
  const temp = node.left
  node.left = node.right
  node.right = temp
}

const invertTree = root => {
  if (!root) return root
  const stk = [root]

  while (stk.length) {
    let node = stk.pop()

    if (node) {
      node.right && stk.push(node.right)
      node.left && stk.push(node.left)
      stk.push(node)
      stk.push(null)
    } else {
      node = stk.pop()
      reverse(node)
    }
  }
  return root
}

const root = {
  val: 1,
  left: {
    val: 2,
    left: null,
    right: null
  },
  right: {
    val: 3,
    left: null,
    right: null
  }
}

console.log(invertTree(root))